﻿using Day27Auth.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;

namespace Day27Auth.Framework
{
    public class ActionVirtualFile : VirtualFile
    {
        //private readonly Func<string> _contentFactory;
        private readonly string _path;

        public ActionVirtualFile(string path) : base(path)
        {
            _path = path;
            //_contentFactory = contentFactory;
        }
        public override Stream Open()
        {
            var writer1 = new StringWriter();
            AngularJSController c = new AngularJSController();
            //Create fake http context to render the view
            var fakeResponse = new HttpResponse(writer1);
            var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "AngularJS");
            routeData.Values.Add("action", "Routes");
            var fakeHttpContext = new HttpContextWrapper(fakeContext);
            var fakeControllerContext = new ControllerContext(
                fakeHttpContext,
                routeData, c);

            PartialViewResult r = c.Routes() as PartialViewResult;
            r.ExecuteResult(fakeControllerContext);
            
            //var rc = new RequestContext(fakeHttpContext, routeData);
            //(c as IController).Execute(rc);
            
            //var viewContext = new ViewContext(fakeControllerContext, r.View, c.ViewData, c.TempData, writer1);
            //r.View.Render(viewContext, writer1);
            //viewResult.ViewEngine.ReleaseView(fakeControllerContext, viewResult.View);
            string response = writer1.ToString();
            //Remove the script tag
            response = response.Replace("<script>", "").Replace("</script>", "");
            byte[] byteArray = Encoding.UTF8.GetBytes(response);
            MemoryStream stream = new MemoryStream(byteArray);

            return stream;

            //var viewResult = ViewEngines.Engines.FindPartialView(c.ControllerContext,
            //                                                 viewName);
            //var viewContext = new ViewContext(c.ControllerContext, viewResult.View,
            //                             ViewData, TempData, stream);
            //viewResult.View.Render(viewContext, stream);
            //viewResult.ViewEngine.ReleaseView(c.ControllerContext, viewResult.View);
        }
    }
}